package net.ideapad.struts.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.ideapad.data.Group;
import net.ideapad.hibernate.HibernateSessionFactory;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;

/**
 * Action class for listing all the groups a user belongs to.
 * 
 * MyEclipse Struts Creation date: 12-12-2009
 * 
 * XDoclet definition:
 * 
 * @struts.action path="/viewGroups" name="viewGroupsForm"
 *                input="/form/viewGroups.jsp" scope="request" validate="true"
 * @struts.action-forward name="viewGroups" path="/form/viewGroups.jsp"
 */
public class ViewGroupsAction extends Action {
	/**
	 * Method that provides all the data to the jsp about the groups a user belongs to.
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		Integer userID = (Integer) request.getSession().getAttribute("userID");

		if (userID != null) {
			Session session = HibernateSessionFactory.getSession();

			session.beginTransaction();

			@SuppressWarnings("unchecked")
			List<Group> topGroups = session.createQuery("select g from Group g left join fetch g.usersInGroup as ug where ug.userId = :id AND g.parentGroup = NULL").setInteger("id", userID).list();

			request.setAttribute("TopGroups", topGroups);
			session.getTransaction().commit();

			session.beginTransaction();

			@SuppressWarnings("unchecked")
			List<Group> groups = session.createQuery("select g from Group g left join fetch g.usersInGroup as ug left join fetch g.parentGroup where ug.userId = :id AND g.parentGroup != NULL").setInteger("id", userID).list();

			request.setAttribute("OtherGroups", groups);

			session.getTransaction().commit();
			HibernateSessionFactory.closeSession();
		}

		return mapping.findForward("viewGroups");
	}
}